import React, { Component } from 'react'
import request from '../../utils/request'

export default class Header extends Component {
  state = {
    name: '',
  }
  // 收集数据
  handleChange = (e) => {
    this.setState({ name: e.target.value })
  }
  // 键盘抬起
  handleUp = async (e) => {
    if (e.keyCode === 13) {
      if (this.state.name.trim().length === 0) return alert('不能为空')
      // !后端确实添加好了
      await request.post('/', {
        name: this.state.name,
        done: false, // 未完成
      })
      // 调用父亲获取数据并重新渲染的方法
      this.props.getList()
      // 清空输入的内容
      this.setState({ name: '' })
    }
  }
  render() {
    return (
      <header className='header'>
        <h1>todos</h1>
        <input
          className='new-todo'
          placeholder='What needs to be done?'
          value={this.state.name}
          onChange={this.handleChange}
          autoFocus
          onKeyUp={this.handleUp}
        />
      </header>
    )
  }
}
